package com.cheyunkeji.er.activity.evaluate;

import android.Manifest;
import android.content.Intent;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.cheyun.netsalev3.R;
import com.cheyunkeji.er.Constants;
import com.cheyun.netsalev3.MyApplication;
import com.cheyunkeji.er.MyFragmentManager;
import com.cheyunkeji.er.adapter.evaluate.MenuNavigatorAdapter;
import com.cheyunkeji.er.base.BaseActivity;
import com.cheyunkeji.er.bean.evaluate.EvaluateDetailResult2;
import com.cheyunkeji.er.bean.event.RefreshUIEvent;
import com.cheyunkeji.er.fragment.evaluate.AppearanceCheckFragment;
import com.cheyunkeji.er.fragment.evaluate.CarBaseInfoFragment;
import com.cheyunkeji.er.fragment.evaluate.CarConfigInfoFragment;
import com.cheyunkeji.er.fragment.evaluate.CarFrameworkCheckFragment;
import com.cheyunkeji.er.fragment.evaluate.CarLacquerCheckFragment;
import com.cheyunkeji.er.fragment.evaluate.CheckResultPz;
import com.cheyunkeji.er.fragment.evaluate.DiPanCheckFragment;
import com.cheyunkeji.er.fragment.evaluate.DriveCabinCheckFragment;
import com.cheyunkeji.er.fragment.evaluate.EngineCabinCheckFragment;
import com.cheyunkeji.er.fragment.evaluate.EvaluateBaseInfoFragment;
import com.cheyunkeji.er.fragment.evaluate.FunctionalityPartsCheckFragment;
import com.cheyunkeji.er.fragment.evaluate.RoadTestCheckFragment;
import com.cheyunkeji.er.fragment.evaluate.StartCheckFragment;
import com.cheyunkeji.er.fragment.evaluate.TakeCarPhotoFragment;
import com.cheyunkeji.er.fragment.evaluate.TyreCheckFragment;
import com.cheyunkeji.er.http.ApiClient;
import com.cheyunkeji.er.http.HttpConstants;
import com.cheyunkeji.er.http.RespCallback;
import com.cheyunkeji.er.utils.StrUtil;
import com.cheyunkeji.er.view.SDialog;
import com.cheyunkeji.er.view.SToast;
import com.cheyunkeji.er.view.evaluate.NoScrollViewPager;
import com.google.gson.Gson;
import com.ogaclejapan.smarttablayout.utils.v4.FragmentPagerItemAdapter;
import com.ogaclejapan.smarttablayout.utils.v4.FragmentPagerItems;
import com.zhy.http.okhttp.callback.StringCallback;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;

import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;

import androidx.core.view.GravityCompat;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.viewpager.widget.ViewPager;
import butterknife.BindView;
import butterknife.ButterKnife;
import okhttp3.Call;
import okhttp3.Request;
import pub.devrel.easypermissions.AfterPermissionGranted;
import pub.devrel.easypermissions.AppSettingsDialog;
import pub.devrel.easypermissions.EasyPermissions;

import static android.Manifest.permission.ACCESS_FINE_LOCATION;
import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE;

public class EvaluateWorkflowActivity extends BaseActivity
    implements EasyPermissions.PermissionCallbacks,
        AdapterView.OnItemClickListener,
        DrawerLayout.DrawerListener {

  private static final String TAG = EvaluateWorkflowActivity.class.getSimpleName();
  private static final int REQUEST_NECESSARY_PMS_CODE = 0X110;

  @BindView(R.id.iv_upload)
  ImageView iv_upload;

  @BindView(R.id.vp_content)
  NoScrollViewPager vpContent;

  @BindView(R.id.activity_evaluate_workflow)
  LinearLayout activityEvaluateWorkflow;

  @BindView(R.id.iv_back)
  ImageView ivBack;

  @BindView(R.id.vTitle)
  TextView vTitle;
  //    @BindView(R.id.iv_save)
  //    ImageView ivSave;
  @BindView(R.id.iv_menu)
  ImageView ivMenu;

  @BindView(R.id.lv_menu)
  ListView lvMenu;

  @BindView(R.id.drawer_layout)
  DrawerLayout drawerLayout;

  private SDialog dialog;
  String[] perms = {
    Manifest.permission.CAMERA, ACCESS_FINE_LOCATION, WRITE_EXTERNAL_STORAGE
  }; // 权限列表

  public int getEvaluateArchiveType() {
    return evaluateArchiveType;
  }

  //    当前评估类型 ： 1.新建 2.未上传待评估 3.已评估待编辑
  private int evaluateArchiveType;

  private MenuNavigatorAdapter menuNavigatorAdapter;

  //    侧滑导航菜单标题
  private ArrayList<String> menuIndexDescs;

  private List<Integer> iroute=new ArrayList<>(Arrays.asList(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0));

  public String getCURRENT_TO_UPLOAD_RESULT_URL() {
    return CURRENT_TO_UPLOAD_RESULT_URL;
  }

  //    当前保存评估结果链接  1.插入、新增  2.已上传编辑
  private String CURRENT_TO_UPLOAD_RESULT_URL = HttpConstants.INSERT_ARCHIVE_INFO;

  private Class[] classArray = {
    EvaluateBaseInfoFragment.class,
    CarBaseInfoFragment.class,
    CarConfigInfoFragment.class,
    TakeCarPhotoFragment.class,
    CarFrameworkCheckFragment.class,
    AppearanceCheckFragment.class,
    CarLacquerCheckFragment.class,
    TyreCheckFragment.class,
    EngineCabinCheckFragment.class,
    DriveCabinCheckFragment.class,
    StartCheckFragment.class,
    RoadTestCheckFragment.class,
    DiPanCheckFragment.class,
    FunctionalityPartsCheckFragment.class,
    CheckResultPz.class
  };
  //   当前显示的Fragment的下标
  private int CURRENT_PAGE_INDEX = 0;
  private FragmentPagerItemAdapter vpFragsAdapter;
  private String[] tabTitles;

  // 订阅方法，当接收到事件的时候，会调用该方法
  @Subscribe(threadMode = ThreadMode.MAIN)
  public void onEvent(JSONObject obj) {
    //        //设置未填写完整数据
    //        menuNavigatorAdapter.setDefect(getIroute);
    //        Toast.makeText(this, getIroute.toString(), Toast.LENGTH_SHORT).show();
    JumpView(obj);
  }

  @Override
  protected void init() {
    setContentView(R.layout.er_activity_evaluate_workflow);
    ButterKnife.bind(this);
    tabTitles = getResources().getStringArray(R.array.evaluate_workflow_tabtitles);
    requestNecessaryPms();
    // 注册成为订阅者
    EventBus.getDefault().register(this);
  }

  @Override
  protected void initView() {
    vTitle.setText("1.评估基本信息");
    ivBack.setOnClickListener(this);
    ivMenu.setOnClickListener(this);
    iv_upload.setOnClickListener(this);

    vpFragsAdapter =
        new FragmentPagerItemAdapter(
            getSupportFragmentManager(),
            FragmentPagerItems.with(this)
                .add(tabTitles[0], EvaluateBaseInfoFragment.class)
                .add(tabTitles[1], CarBaseInfoFragment.class)
                .add(tabTitles[2], CarConfigInfoFragment.class)
                .add(tabTitles[3], TakeCarPhotoFragment.class)
                .add(tabTitles[4], CarFrameworkCheckFragment.class)
                .add(tabTitles[5], AppearanceCheckFragment.class)
                .add(tabTitles[6], CarLacquerCheckFragment.class)
                .add(tabTitles[7], TyreCheckFragment.class)
                .add(tabTitles[8], EngineCabinCheckFragment.class)
                .add(tabTitles[9], DriveCabinCheckFragment.class)
                .add(tabTitles[10], StartCheckFragment.class)
                .add(tabTitles[11], RoadTestCheckFragment.class)
                .add(tabTitles[12], DiPanCheckFragment.class)
                .add(tabTitles[13], FunctionalityPartsCheckFragment.class)
                .add(tabTitles[14], CheckResultPz.class)
                .create());
    vpContent.setAdapter(vpFragsAdapter);

    vpContent.setOnPageChangeListener(
        new ViewPager.OnPageChangeListener() {
          @Override
          public void onPageScrolled(
              int position, float positionOffset, int positionOffsetPixels) {}

          @Override
          public void onPageSelected(int position) {

            CURRENT_PAGE_INDEX = position;

            switch (position) {
              case EvaluateBaseInfoFragment.PAGE_INDEX:
                setTitleDesc(StrUtil.getString(R.string.check_item_1));
                break;
              case CarBaseInfoFragment.PAGE_INDEX:
                setTitleDesc(StrUtil.getString(R.string.check_item_2));
                break;
              case CarConfigInfoFragment.PAGE_INDEX:
                setTitleDesc(StrUtil.getString(R.string.check_item_3));
                break;
              case TakeCarPhotoFragment.PAGE_INDEX:
                setTitleDesc(StrUtil.getString(R.string.check_item_4));
                break;
              case CarFrameworkCheckFragment.PAGE_INDEX:
                setTitleDesc(StrUtil.getString(R.string.check_item_5));
                break;
              case CarLacquerCheckFragment.PAGE_INDEX:
                setTitleDesc(StrUtil.getString(R.string.check_item_7));
                break;
              case TyreCheckFragment.PAGE_INDEX:
                setTitleDesc(StrUtil.getString(R.string.check_item_8));
                break;
              case EngineCabinCheckFragment.PAGE_INDEX:
                setTitleDesc(StrUtil.getString(R.string.check_item_9));
                break;
              case DriveCabinCheckFragment.PAGE_INDEX:
                setTitleDesc(StrUtil.getString(R.string.check_item_10));
                break;
              case StartCheckFragment.PAGE_INDEX:
                setTitleDesc(StrUtil.getString(R.string.check_item_11));
                break;
              case RoadTestCheckFragment.PAGE_INDEX:
                setTitleDesc(StrUtil.getString(R.string.check_item_12));
                break;
              case DiPanCheckFragment.PAGE_INDEX:
                setTitleDesc(StrUtil.getString(R.string.check_item_13));
                break;
              case FunctionalityPartsCheckFragment.PAGE_INDEX:
                setTitleDesc(StrUtil.getString(R.string.check_item_14));
                break;
              case CheckResultPz.PAGE_INDEX:
                setTitleDesc(StrUtil.getString(R.string.check_item_15));
                break;
              case AppearanceCheckFragment.PAGE_INDEX:
                setTitleDesc(StrUtil.getString(R.string.check_item_6));
                break;
              default:
                break;
            }
          }

          @Override
          public void onPageScrollStateChanged(int state) {}
        });

    //       根据传过来的Index设置当前应该显示的页面
    Log.d("***************","initView:"+getIntent().getIntExtra("PAGE_INDEX", 0));
    setCurrentPage(getIntent().getIntExtra("PAGE_INDEX", 0));

    initMenuNavigator();
  }

  private void initMenuNavigator() {
    //       初始化侧滑菜单
    menuIndexDescs =
        new ArrayList<>(
            Arrays.asList(getResources().getStringArray(R.array.evaluate_workflow_tabtitles)));
    menuNavigatorAdapter = new MenuNavigatorAdapter(menuIndexDescs, this);
    menuNavigatorAdapter.setDefect(iroute);
    lvMenu.setAdapter(menuNavigatorAdapter);

    lvMenu.setOnItemClickListener(this);
    drawerLayout.addDrawerListener(this);
  }

  @Override
  protected void initData() {
    evaluateArchiveType =
        getIntent()
            .getIntExtra(
                Constants.EVALUATE_ARCHIVE_TYPE, Constants.ARCHIVE_TYPE_CREATE_NEW_EVALUATE);

    if (evaluateArchiveType == Constants.ARCHIVE_TYPE_CREATE_NEW_EVALUATE
        || evaluateArchiveType == Constants.ARCHIVE_TYPE_UN_UPLOAD_TO_EVALUATE
        || evaluateArchiveType == Constants.ARCHIVE_TYPE_WITH_FAST_EVALUATE_VIN) {
      CURRENT_TO_UPLOAD_RESULT_URL = HttpConstants.INSERT_ARCHIVE_INFO;
    } else if (evaluateArchiveType == Constants.ARCHIVE_TYPE_UPLOADED_TO_EDIT) {
      CURRENT_TO_UPLOAD_RESULT_URL = HttpConstants.UPDATE_ARCHIVE_INFO;
    }

    Log.e(TAG, "initData: 当前上传数据URL : " + CURRENT_TO_UPLOAD_RESULT_URL);

    //        两种情况下有AID传递过来 ： 1.已保存未上传的评估记录 2.已上传待编辑的评估记录
    if (!TextUtils.isEmpty(getIntent().getStringExtra("AID"))) {
      String aid = getIntent().getStringExtra("AID");
      loadCarEvaluateResult(aid);
      Log.e(TAG, "================ initData: aid : ================= " + aid);
    }

    if (!TextUtils.isEmpty(getIntent().getStringExtra("VIN"))) {
      //            将VIN传给评估基本信息页面
      EventBus.getDefault()
          .postSticky(
              new RefreshUIEvent(
                  getIntent().getStringExtra("VIN"), RefreshUIEvent.TYPE_REFRESH_FILL_VIN));
      Log.e(TAG, "initData: 发送Sticky消息 VIN :  " + getIntent().getStringExtra("VIN"));
    }
  }

  /** 根据未填写页数跳转 */
  public void JumpIndex() {
    final int index = getIntent().getIntExtra("index", -1);
    Log.d("***************","JumpIndex:"+getIntent().getIntExtra("index", -1));
    if (index != -1) {
      //            先保存，再跳转
      ((OnOutActionListener)
              MyFragmentManager.getInstance().getFrag(classArray[CURRENT_PAGE_INDEX]))
          .onSaveEvaluateResult(
              new Runnable() {
                @Override
                public void run() {
                  setCurrentPage(index);
                }
              });
    }
  }

  /**
   * 根据vid获取已保存的车辆评估信息
   *
   * @param aid
   */
  private void loadCarEvaluateResult(String aid) {

    HashMap<String, String> params = new HashMap<>();
    //        params.put("authkey",
    // UserInfoManager.getInstance(MyApplication.getInstance()).getAuthKey());
    //        params.put(ChannelInfoUtil.getCurrentChannelInfo().getCkey1().getYkey(),
    // ChannelInfoUtil.getCurrentChannelInfo().getCkey1().getY7e_e73a691f02a46500201c3998e6a2989d());
    params.put("aid", aid);

    ApiClient.postForm(
        HttpConstants.GET_EVALUATE_DETAIL_INFO,
        params,
        new RespCallback<EvaluateDetailResult2>() {

          @Override
          protected void onRequestFailed(String msg) {
            SToast.show(msg);
          }

          @Override
          protected void onSuccess(EvaluateDetailResult2 data) {

            if (null != data) {
              //                    MyApplication 缓存
              MyApplication.getInstance().setEvaluateResult(data);
              Log.e(TAG, "onSuccess: 评估结果Json 数据 ：" + new Gson().toJson(data));
              //                  通知Fragment页面刷新
              EventBus.getDefault()
                  .post(new RefreshUIEvent(RefreshUIEvent.TYPE_REFRESH_EVAL_RESULT));
              JumpIndex();
              menuNavigatorAdapter.setDefect(data.getIroute());
            }
          }

          @Override
          public void onBefore(Request request, int id) {
            showDialog();
          }

          @Override
          public void onAfter(int id) {
            dismissDialog();
          }
        });
  }

  @AfterPermissionGranted(REQUEST_NECESSARY_PMS_CODE)
  private void requestNecessaryPms() {
    if (EasyPermissions.hasPermissions(this, perms)) {

    } else {
      // Do not have permissions, request them now
      //            EasyPermissions.requestPermissions(this,
      // getString(R.string.request_necessary_pms),
      //                    REQUEST_NECESSARY_PMS_CODE, perms);
      EasyPermissions.requestPermissions(this, "需要获取位置，拍照，存储权限", REQUEST_NECESSARY_PMS_CODE, perms);
    }
  }

  @Override
  public void onRequestPermissionsResult(
      int requestCode, String[] permissions, int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
  }

  @Override
  public void onPermissionsGranted(int requestCode, List<String> perms) {}

  @Override
  public void onPermissionsDenied(int requestCode, List<String> perms) {
    if (EasyPermissions.somePermissionPermanentlyDenied(this, perms)) {

      //            new AppSettingsDialog.Builder(this).build().show();
      new AppSettingsDialog.Builder(this)
          .setRationale("没有该权限，此应用程序可能无法正常工作。打开应用设置界面以修改应用权限")
          .setTitle("必需权限")
          .build()
          .show();
    } else if (!EasyPermissions.hasPermissions(this, this.perms)) {
      // 这里响应的是除了AppSettingsDialog这个弹出框，剩下的两个弹出框被拒绝或者取消的效果
      quitEvaluateWorkflow();
    }
  }

  @Override
  protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == AppSettingsDialog.DEFAULT_SETTINGS_REQ_CODE) {
      if (!EasyPermissions.hasPermissions(this, perms)) {
        // 这里响应的是AppSettingsDialog点击取消按钮的效果
        quitEvaluateWorkflow();
      }
    }
  }

  public void setCurrentPage(int index) {
    Log.d("***************","setCurrentPage:"+index);
    if (vpContent != null) {
      vpContent.setCurrentItem(index, true);
      iroute.set(index,1);
    }
  }

  //    用于Fragment设置标题
  public void setTitleDesc(String titleDesc) {
    if (!TextUtils.isEmpty(titleDesc)) vTitle.setText(titleDesc);
  }

  @Override
  public void onClick(View v) {
    switch (v.getId()) {

        //            case R.id.iv_save:
        //
        //                Log.e(TAG, "onClick: " + CURRENT_PAGE_INDEX);
        //
        ////                点击保存按钮，通知Fragment上传评估信息
        //                ((OnOutActionListener)
        // MyFragmentManager.getInstance().getFrag(classArray[CURRENT_PAGE_INDEX])).onSaveEvaluateResult(null);
        //
        //                break;
      case R.id.iv_menu:
        if (drawerLayout.isDrawerOpen(GravityCompat.END)) {
          drawerLayout.closeDrawer(GravityCompat.END);
        } else {
          drawerLayout.openDrawer(GravityCompat.END);
        }
        break;
      case R.id.iv_upload:
        //            先保存，再跳转
        ((OnOutActionListener)
                MyFragmentManager.getInstance().getFrag(classArray[CURRENT_PAGE_INDEX]))
            .onSaveEvaluateResult(
                new Runnable() {
                  @Override
                  public void run() {
                    uploadEvaluateReport();
                  }
                });

        break;

      case R.id.iv_back:
        quitEvaluateWorkflow();
        break;

      default:
        break;
    }
  }

  private void uploadEvaluateReport() {
    HashMap<String, String> params = new HashMap<>();
    if (MyApplication.getInstance().getEvaluateResult() == null) {
      SToast.show("请完善信息!");
      return;
    }
    params.put("aid", MyApplication.getInstance().getEvaluateResult().getAid());

    ApiClient.postForm(
        HttpConstants.UP_TO_ARCHIVE_INFO,
        params,
        new StringCallback() {

          @Override
          public void onError(Call call, Exception e, int id) {
            // 网络异常
            if (e instanceof UnknownHostException || e instanceof SocketException) {
              SToast.show(R.string.tip_network_error, Gravity.CENTER);
              return;
            }
          }

          @Override
          public void onResponse(String response, int id) {

            Log.e(TAG, "onResponse: 检查结果批注： " + response);

            try {
              final JSONObject obj = new JSONObject(response);
              if (1 == obj.optInt("code", 0)) {
                SToast.show("上传成功！");
                MyApplication.getInstance().clearEvaluateResult();
                finish();
              } else {
                String[] strings = obj.optString("msg").split("\\.");
                if(strings.length>1){
                  dialog =
                          new SDialog(
                                  EvaluateWorkflowActivity.this,
                                  "温馨提示",
                                  obj.optString("msg"),
                                  R.string.t_supplement,
                                  R.string.t_cancel,
                                  new SDialog.SDialog2Listener() {
                                    @Override
                                    public void onClick(boolean l, View view) {
                                      // true：左按钮 false：右按钮
                                      if (l) {
                                        JumpView(obj);
                                      }
                                    }
                                  });
                }else{
                  dialog = new SDialog(EvaluateWorkflowActivity.this,
                          "温馨提示",
                          obj.optString("msg"),
                          "确定", new SDialog.SDialogListener() {
                    @Override
                    public void onOK() {
                      dialog.dismiss();
                    }
                  });
                }
//                if (null == dialog) {
//                  dialog =
//                      new SDialog(
//                          EvaluateWorkflowActivity.this,
//                          "温馨提示",
//                          obj.optString("msg"),
//                          R.string.t_supplement,
//                          R.string.t_cancel,
//                          new SDialog.SDialog2Listener() {
//                            @Override
//                            public void onClick(boolean l, View view) {
//                              // true：左按钮 false：右按钮
//                              if (l) {
//                                JumpView(obj);
//                              }
//                            }
//                          });
//                } else {
//                  dialog.setContent(obj.optString("msg"));
//                }
                dialog.show();
              }

            } catch (JSONException e) {
              e.printStackTrace();
            }
          }
        });
  }

  /**
   * 切换界面
   *
   * @param obj
   */
  private void JumpView(JSONObject obj) {
    String[] strings = obj.optString("msg").split("\\.");
    Log.d("***************","JumpView:"+obj.optString("msg"));
    if (strings.length > 1) {
      final int index = Integer.parseInt(strings[0]) - 1;
      menuNavigatorAdapter.changeSelected(index);
      lvMenu.setItemChecked(index, true);
      Log.d("***************","JumpView,index:"+index+",getCurrentItem:"+vpContent.getCurrentItem());
      if (index != vpContent.getCurrentItem()) {
        //            先保存，再跳转
        ((OnOutActionListener)
                MyFragmentManager.getInstance().getFrag(classArray[CURRENT_PAGE_INDEX]))
            .onSaveEvaluateResult(
                new Runnable() {
                  @Override
                  public void run() {
                    setCurrentPage(index);
                  }
                });
      }
    }
  }

  @Override
  protected void onDestroy() {
    super.onDestroy();
    MyApplication.getInstance().clearEvaluateResult();
    // 解除注册
    EventBus.getDefault().unregister(this);
  }

  @Override
  public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
    //        点击菜单后改变侧滑菜单当前选中位置状态
    menuNavigatorAdapter.changeSelected(position);
    //        关闭侧滑菜单
    if (drawerLayout.isDrawerOpen(GravityCompat.END)) {
      drawerLayout.closeDrawers();
    }
  }

  @Override
  public void onDrawerSlide(View drawerView, float slideOffset) {}

  @Override
  public void onDrawerOpened(View drawerView) {
    lvMenu.setItemChecked(vpContent.getCurrentItem(), true);
    menuNavigatorAdapter.changeSelected(vpContent.getCurrentItem());
    lvMenu.smoothScrollToPosition(vpContent.getCurrentItem());
  }

  @Override
  public void onDrawerClosed(View drawerView) {
    Log.d("***************","onDrawerClosed,lvMenu.getCheckedItemPosition():"+lvMenu.getCheckedItemPosition()+",vpContent.getCurrentItem():"+vpContent.getCurrentItem());
    if (lvMenu.getCheckedItemPosition() != vpContent.getCurrentItem()) {
      //            先保存，再跳转
      ((OnOutActionListener)
              MyFragmentManager.getInstance().getFrag(classArray[CURRENT_PAGE_INDEX]))
          .onSaveEvaluateResult(
              new Runnable() {
                @Override
                public void run() {
                  Log.d("***************","onDrawerClosed,lvMenu.getCheckedItemPosition():"+lvMenu.getCheckedItemPosition());
                  setCurrentPage(lvMenu.getCheckedItemPosition());
                }
              });
    }
  }

  //  返回退出评估页面前，需要进行保存
  @Override
  public void onBackPressed() {
    quitEvaluateWorkflow();
  }

  private void quitEvaluateWorkflow() {
    ((OnOutActionListener) MyFragmentManager.getInstance().getFrag(classArray[CURRENT_PAGE_INDEX]))
        .onSaveEvaluateResult(new ExitRunnable());
  }

  @Override
  public void onDrawerStateChanged(int newState) {}

  /** Activity外部事件接口回调 */
  public interface OnOutActionListener {

    /** Activity 页面保存按钮触发，通知Fragment保存数据 */
    void onSaveEvaluateResult(Runnable uiTask);
  }

  public class ExitRunnable implements Runnable {
    @Override
    public void run() {
      MyApplication.getInstance().removeActivity(EvaluateWorkflowActivity.class);
      finish();
    }
  }
}
